package compressutil

import (
	"archive/zip"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

func ZipDir(dir string, saveFullpath string, containsSelf bool) error {
	file, err := os.OpenFile(saveFullpath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
	if nil != err {
		return err
	}
	defer file.Close()

	writer := zip.NewWriter(file)
	defer writer.Close()

	err = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
		if nil != err {
			return err
		}
		if filepath.Clean(path) == filepath.Clean(dir) {
			return nil
		}

		// 压缩包内的相对路径
		ind := len(dir + "\\")
		if containsSelf {
			ind = len(filepath.Dir(dir) + "\\")
		}
		itemName := strings.ReplaceAll(path[ind:], "/", "\\")

		if d.IsDir() {
			return nil
		}

		subWriter, err := writer.CreateHeader(&zip.FileHeader{
			Name:    itemName,
			Method:  zip.Deflate,
			Comment: "gmap",
		})
		if nil != err {
			return err
		}

		fileReader, err := os.Open(path)
		if nil != err {
			return err
		}
		defer fileReader.Close()

		_, err = io.Copy(subWriter, fileReader)
		if nil != err {
			return err
		}
		return nil
	})
	if nil != err {
		return err
	}
	return nil
}
